<template>
  <div class="app-container">
    <!-- 查询表单 - 布局优化和tooltip -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <!-- ... (原有的查询表单代码) ... -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="设备ID" prop="deviceId">
            <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入设备ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="故障标题" prop="faultTitle">
            <el-input
                v-model="queryParams.faultTitle"
                placeholder="请输入故障标题"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="faultLevel">
            <template #label>
              <el-tooltip content="1-紧急,2-重要,3-一般" placement="top">
                <span>故障等级</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.faultLevel" placeholder="请选择故障等级" clearable style="width: 100%;">
              <el-option
                  v-for="dict in fault_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="报修人" prop="reportBy">
            <el-input
                v-model="queryParams.reportBy"
                placeholder="请输入报修人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="报修时间" prop="reportTime">
            <el-date-picker clearable
                            v-model="queryParams.reportTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择报修时间"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="status">
            <template #label>
              <el-tooltip content="0-待处理,1-处理中,2-已解决,3-已关闭" placement="top">
                <span>故障状态</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.status" placeholder="请选择故障状态" clearable style="width: 100%;">
              <el-option
                  v-for="dict in fault_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计图表区域 -->
    <el-card class="box-card mb8 chart-section">
      <template #header>
        <div class="card-header">
          <span>故障报修概览统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div id="faultLevelChart" class="chart-container"></div>
        </el-col>
        <el-col :span="12">
          <div id="faultStatusChart" class="chart-container"></div>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['fault:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['fault:report:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['fault:report:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['fault:report:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格 - 列宽优化和tooltip -->
    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="故障ID" align="center" prop="id" width="80" />
      <el-table-column label="设备ID" align="center" prop="deviceId" width="90" />
      <el-table-column label="故障标题" align="center" prop="faultTitle" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="故障描述" align="center" prop="faultDesc" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="faultLevel" width="100">
        <template #header>
          <el-tooltip content="1-紧急,2-重要,3-一般" placement="top">
            <span>故障等级</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="fault_level" :value="scope.row.faultLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="报修人" align="center" prop="reportBy" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="报修时间" align="center" prop="reportTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="status" width="100">
        <template #header>
          <el-tooltip content="0-待处理,1-处理中,2-已解决,3-已关闭" placement="top">
            <span>故障状态</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="fault_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- 考虑添加一个关联的处理状态或进展概览列，但需后端提供聚合数据 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fault:report:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fault:report:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改故障报修对话框 - 尺寸、布局优化和tooltip -->
    <el-dialog :title="title" v-model="open" width="980px" append-to-body>
      <el-form ref="reportRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障标题" prop="faultTitle">
              <el-input v-model="form.faultTitle" placeholder="请输入故障标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="faultLevel">
              <template #label>
                <el-tooltip content="1-紧急,2-重要,3-一般" placement="top">
                  <span>故障等级</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.faultLevel" placeholder="请选择故障等级" style="width: 100%;">
                <el-option
                    v-for="dict in fault_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报修人" prop="reportBy">
              <el-input v-model="form.reportBy" placeholder="请输入报修人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报修时间" prop="reportTime">
              <el-date-picker clearable
                              v-model="form.reportTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择报修时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <el-tooltip content="0-待处理,1-处理中,2-已解决,3-已关闭" placement="top">
                  <span>故障状态</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.status" placeholder="请选择故障状态" style="width: 100%;">
                <el-option
                    v-for="dict in fault_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="故障描述" prop="faultDesc">
          <el-input v-model="form.faultDesc" type="textarea" :rows="4" placeholder="请输入故障描述内容" />
        </el-form-item>

        <el-divider content-position="left">故障处理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddFaultRepair">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteFaultRepair">删除</el-button>
          </el-col>
        </el-row>
        <!-- 子表格 - 列宽优化、tooltip和max-height -->
        <el-table :data="faultRepairList" :row-class-name="rowFaultRepairIndex" @selection-change="handleFaultRepairSelectionChange" ref="faultRepair" max-height="250px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column prop="repairResult" width="120">
            <template #header>
              <el-tooltip content="1-已修复,2-未修复,3-无法修复" placement="top">
                <span>处理结果</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.repairResult" placeholder="请选择结果">
                <el-option
                    v-for="dict in fault_result"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="处理描述" prop="repairDesc" min-width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.repairDesc" type="textarea" :rows="1" placeholder="请输入描述" />
            </template>
          </el-table-column>
          <el-table-column label="处理方法" prop="repairMethod" min-width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.repairMethod" type="textarea" :rows="1" placeholder="请输入方法" />
            </template>
          </el-table-column>
          <el-table-column label="开始时间" prop="startTime" width="160">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.startTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="完成时间" prop="endTime" width="160">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.endTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择完成时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="repairHours" width="100">
            <template #header>
              <el-tooltip content="单位为小时" placement="top">
                <span>处理耗时</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.repairHours" placeholder="请输入耗时" />
            </template>
          </el-table-column>
          <el-table-column label="处理人" prop="repairBy" width="100" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.repairBy" placeholder="请输入处理人" />
            </template>
          </el-table-column>
          <el-table-column prop="status" width="120">
            <template #header>
              <el-tooltip content="0-待处理,1-处理中,2-已完成" placement="top">
                <span>处理状态</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option
                    v-for="dict in fault_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Report">
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/fault/report"
import * as echarts from 'echarts'; // 引入 ECharts

const { proxy } = getCurrentInstance()
const { fault_level, fault_result, fault_status } = proxy.useDict('fault_level', 'fault_result', 'fault_status')

const reportList = ref([])
const faultRepairList = ref([]) // 子表数据
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedFaultRepair = ref([]) // 子表选中项
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// ECharts 实例引用
let faultLevelChartInstance = null;
let faultStatusChartInstance = null;

const data = reactive({
  form: {
    // 确保faultRepairList在form中初始化
    faultRepairList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: null,
    faultTitle: null,
    faultDesc: null,
    faultLevel: null,
    reportBy: null,
    reportTime: null,
    status: null,
  },
  rules: {
    deviceId: [
      { required: true, message: "设备ID不能为空", trigger: "blur" }
    ],
    faultTitle: [
      { required: true, message: "故障标题不能为空", trigger: "blur" }
    ],
    faultDesc: [
      { required: true, message: "故障描述不能为空", trigger: "blur" }
    ],
    faultLevel: [
      { required: true, message: "故障等级不能为空", trigger: "change" }
    ],
    reportBy: [
      { required: true, message: "报修人不能为空", trigger: "blur" }
    ],
    reportTime: [
      { required: true, message: "报修时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "故障状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/**
 * 节流函数 (如果proxy.$modal没有，可以自己实现一个简易版或引入lodash的throttle)
 * ECharts resize时可能用到
 */
const throttle = (func, delay) => {
  let timeoutId;
  let lastArgs;
  let lastThis;

  return function(...args) {
    lastArgs = args;
    lastThis = this;

    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(lastThis, lastArgs);
        timeoutId = null;
        lastArgs = null;
        lastThis = null;
      }, delay);
    }
  };
};

/**
 * 根据数据聚合图表所需的数据
 * @param {Array} dataList - 报修列表数据
 */
function aggregateChartData(dataList) {
  if (!dataList || dataList.length === 0) {
    // 数据为空时，清空图表并显示无数据状态
    updateFaultLevelChart([]);
    updateFaultStatusChart([]);
    return;
  }

  const levelCounts = {};
  const statusCounts = {};

  dataList.forEach(item => {
    // 聚合故障等级
    const levelDict = fault_level.value.find(d => parseInt(d.value) === item.faultLevel);
    const levelLabel = levelDict ? levelDict.label : '未知等级';
    levelCounts[levelLabel] = (levelCounts[levelLabel] || 0) + 1;

    // 聚合故障状态
    const statusDict = fault_status.value.find(d => parseInt(d.value) === item.status);
    const statusLabel = statusDict ? statusDict.label : '未知状态';
    statusCounts[statusLabel] = (statusCounts[statusLabel] || 0) + 1;
  });

  const levelSeriesData = Object.keys(levelCounts).map(key => ({
    name: key,
    value: levelCounts[key]
  }));

  const statusSeriesData = Object.keys(statusCounts).map(key => ({
    name: key,
    value: statusCounts[key]
  }));

  // 更新图表
  updateFaultLevelChart(levelSeriesData);
  updateFaultStatusChart(statusSeriesData);
}

/**
 * 初始化并更新故障等级分布图 (饼图)
 * @param {Array} seriesData - 图表数据
 */
function updateFaultLevelChart(seriesData) {
  const chartDom = document.getElementById('faultLevelChart');
  if (!chartDom) return; // 确保DOM元素存在

  if (!faultLevelChartInstance) {
    faultLevelChartInstance = echarts.init(chartDom);
  }

  const option = {
    title: {
      text: '故障等级分布',
      subtext: '基于当前查询结果', // 可以添加副标题说明数据来源
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      // data: seriesData.map(item => item.name) // 数据为空时，legend不显示
    },
    series: [
      {
        name: '故障等级',
        type: 'pie',
        radius: '50%', // 饼图半径
        center: ['50%', '60%'], // 饼图中心位置
        data: seriesData.length > 0 ? seriesData : [{ value: 1, name: '暂无数据', itemStyle: { color: '#ccc' } }], // 无数据时显示占位
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: seriesData.length > 0, // 无数据时不显示标签
          formatter: '{b} ({d}%)'
        },
        labelLine: {
          show: seriesData.length > 0
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }
    ]
  };
  faultLevelChartInstance.setOption(option);
}

/**
 * 初始化并更新故障状态分布图 (柱状图)
 * @param {Array} seriesData - 图表数据
 */
function updateFaultStatusChart(seriesData) {
  const chartDom = document.getElementById('faultStatusChart');
  if (!chartDom) return;

  if (!faultStatusChartInstance) {
    faultStatusChartInstance = echarts.init(chartDom);
  }

  const categories = seriesData.map(item => item.name);
  const values = seriesData.map(item => item.value);

  // 处理无数据情况
  if (seriesData.length === 0) {
    categories.push('暂无数据');
    values.push(0);
  }

  const option = {
    title: {
      text: '故障状态分布',
      subtext: '基于当前查询结果',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        interval: 0, // 强制显示所有标签
        rotate: categories.length > 4 ? 30 : 0 // 当类别多时，旋转标签
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1 // 确保y轴刻度是整数
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: values,
        barWidth: '40%', // 柱子宽度
        itemStyle: {
          color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ]
          )
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        },
        // 无数据时占位，ECharts会自动处理
        markPoint: seriesData.length === 0 ? {
          symbol: 'none',
          label: {
            show: true,
            position: 'inside', // 调整位置
            formatter: '暂无数据',
            fontSize: 14,
            color: '#999'
          },
          data: [{ x: 'center', y: 'center' }] // 放置在图表中心
        } : null
      }
    ]
  };
  faultStatusChartInstance.setOption(option);
}

// 监听窗口大小变化以调整图表尺寸
const resizeCharts = throttle(() => {
  faultLevelChartInstance?.resize();
  faultStatusChartInstance?.resize();
}, 200);

/** 查询故障报修列表 并更新图表*/
function getList() {
  loading.value = true
  listReport(queryParams.value).then(response => {
    reportList.value = response.rows
    total.value = response.total
    loading.value = false
    // 数据加载完成后更新图表
    aggregateChartData(reportList.value);
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceId: null,
    faultTitle: null,
    faultDesc: null,
    faultLevel: null,
    reportBy: null,
    reportTime: null,
    status: null,
    expectFinishTime: null,
    faultRepairList: [] // 重置时清空子列表
  }
  faultRepairList.value = [] // 确保响应式变量也重置
  proxy.resetForm("reportRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加故障报修"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getReport(_id).then(response => {
    form.value = response.data
    // 确保从后端返回的faultRepairList是数组
    faultRepairList.value = response.data.faultRepairList || []
    open.value = true
    title.value = "修改故障报修"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reportRef"].validate(valid => {
    if (valid) {
      form.value.faultRepairList = faultRepairList.value
      if (form.value.id != null) {
        updateReport(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addReport(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除故障报修编号为"' + _ids + '"的数据项？').then(function() {
    return delReport(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 故障处理序号 */
function rowFaultRepairIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 故障处理添加按钮操作 */
function handleAddFaultRepair() {
  let obj = {
    repairDesc: "",
    repairMethod: "",
    repairResult: "",
    startTime: null, // 修正日期字段，初始化为null
    endTime: null,   // 修正日期字段，初始化为null
    repairHours: "",
    repairBy: "",
    status: ""
  }
  faultRepairList.value.push(obj)
}

/** 故障处理删除按钮操作 */
function handleDeleteFaultRepair() {
  if (checkedFaultRepair.value.length === 0) {
    proxy.$modal.msgError("请先选择要删除的故障处理数据")
  } else {
    // 过滤掉选中的行，并重新为剩余行设置索引
    faultRepairList.value = faultRepairList.value.filter(item => !checkedFaultRepair.value.includes(item.index));
    // 清空选中项
    checkedFaultRepair.value = [];
    // 强制刷新表格选中状态，确保UI同步
    proxy.$nextTick(() => {
      proxy.$refs.faultRepair.clearSelection();
    });
  }
}

/** 复选框选中数据 */
function handleFaultRepairSelectionChange(selection) {
  checkedFaultRepair.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('fault/report/export', {
    ...queryParams.value
  }, `report_${new Date().getTime()}.xlsx`)
}

// Mounted 生命周期钩子：初始化图表并添加窗口resize监听
onMounted(() => {
  // 在获取列表数据之前，先初始化空的图表，防止DOM还没渲染好就尝试获取元素
  updateFaultLevelChart([]); // 传入空数组初始化无数据状态
  updateFaultStatusChart([]); // 传入空数组初始化无数据状态

  // 添加窗口resize事件监听
  window.addEventListener('resize', resizeCharts);

  // 第一次加载列表数据
  getList();
});

// Unmounted 生命周期钩子：销毁图表实例并移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  faultLevelChartInstance?.dispose(); // 销毁 ECharts 实例，防止内存泄漏
  faultStatusChartInstance?.dispose();
});

</script>

<style scoped>
/* 可以在这里添加一些样式来微调布局，例如： */
.el-row {
  margin-bottom: 10px; /* 增加行之间的间距，保持视觉平衡 */
}
.el-form-item {
  margin-bottom: 0px; /* 在el-row中已经有间距，减少form-item自带的冗余间距 */
}

/* 统计图表区域样式 */
.chart-section {
  margin-bottom: 20px; /* 图表卡片与下方表格的间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.chart-container {
  height: 300px; /* 为图表设置固定高度 */
  width: 100%; /* 宽度自动填充父容器 */
}
</style>

